// web/src/utils/imageHelper.ts

/**
 * 图片处理工具函数
 */

/**
 * 从文本内容中提取图片URL
 * @param text 待提取的文本
 * @returns 图片URL数组
 */
export function extractImageUrls(text: string): string[] {
  if (!text) return [];

  const urlRegex = /(https?:\/\/[^\s]+\.(?:jpg|jpeg|png|gif|webp|bmp|svg))(?:[\s\)\]\}\']|$)/gi;
  const matches = text.match(urlRegex);
  
  if (!matches) return [];

  // 去重并验证URL格式
  const uniqueUrls = [...new Set(matches)].filter(url => {
    try {
      new URL(url);
      return true;
    } catch {
      return false;
    }
  });

  return uniqueUrls;
}

/**
 * 预览图片（大图查看）
 * @param url 图片URL
 * @param alt 图片描述
 */
export function previewImage(url: string, alt: string = '预览图片'): void {
  // 创建模态框
  const modal = document.createElement('div');
  modal.style.cssText = `
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    background: rgba(0, 0, 0, 0.8);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 10000;
    cursor: zoom-out;
  `;

  // 创建图片元素
  const img = document.createElement('img');
  img.src = url;
  img.alt = alt;
  img.style.cssText = `
    max-width: 90%;
    max-height: 90%;
    object-fit: contain;
    border-radius: 8px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
  `;

  // 点击关闭
  const closeModal = () => {
    document.body.removeChild(modal);
    document.body.style.overflow = '';
  };

  modal.addEventListener('click', (e) => {
    if (e.target === modal) {
      closeModal();
    }
  });

  // ESC键关闭
  const handleKeydown = (e: KeyboardEvent) => {
    if (e.key === 'Escape') {
      closeModal();
      document.removeEventListener('keydown', handleKeydown);
    }
  };

  document.addEventListener('keydown', handleKeydown);
  document.body.style.overflow = 'hidden'; // 防止背景滚动

  modal.appendChild(img);
  document.body.appendChild(modal);
}

/**
 * 下载图片
 * @param url 图片URL
 * @param filename 文件名（可选）
 */
export function downloadImage(url: string, filename?: string): Promise<void> {
  return new Promise((resolve) => {
    const link = document.createElement('a');
    link.href = url;
    link.download = filename || `image_${Date.now()}.jpg`;
    
    // 添加样式隐藏链接
    link.style.display = 'none';
    document.body.appendChild(link);
    
    // 模拟点击下载
    link.click();
    
    // 清理
    setTimeout(() => {
      document.body.removeChild(link);
      resolve();
    }, 100);
  });
}

/**
 * 批量下载图片
 * @param urls 图片URL数组
 * @param baseFilename 基础文件名
 */
export async function downloadImages(urls: string[], baseFilename: string = 'images'): Promise<void> {
  for (let i = 0; i < urls.length; i++) {
    const filename = `${baseFilename}_${i + 1}.jpg`;
    await downloadImage(urls[i], filename);
    
    // 添加延迟避免浏览器限制
    if (i < urls.length - 1) {
      await new Promise(resolve => setTimeout(resolve, 100));
    }
  }
}

/**
 * 检查图片是否有效（可加载）
 * @param url 图片URL
 * @returns Promise<boolean>
 */
export function checkImageValid(url: string): Promise<boolean> {
  return new Promise((resolve) => {
    const img = new Image();
    img.onload = () => resolve(true);
    img.onerror = () => resolve(false);
    img.src = url;
    
    // 超时处理
    setTimeout(() => resolve(false), 5000);
  });
}

/**
 * 批量验证图片URL
 * @param urls 图片URL数组
 * @returns 有效的图片URL数组
 */
export async function validateImageUrls(urls: string[]): Promise<string[]> {
  const validationPromises = urls.map(async (url) => {
    const isValid = await checkImageValid(url);
    return isValid ? url : null;
  });

  const results = await Promise.all(validationPromises);
  return results.filter((url): url is string => url !== null);
}

/**
 * 图片URL转Base64（用于离线缓存）
 * @param url 图片URL
 * @returns Promise<string> Base64字符串
 */
export function imageUrlToBase64(url: string): Promise<string> {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.crossOrigin = 'anonymous';
    
    img.onload = () => {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      
      if (!ctx) {
        reject(new Error('无法获取canvas上下文'));
        return;
      }
      
      canvas.width = img.width;
      canvas.height = img.height;
      ctx.drawImage(img, 0, 0);
      
      try {
        const base64 = canvas.toDataURL('image/jpeg', 0.8);
        resolve(base64);
      } catch (error) {
        reject(error);
      }
    };
    
    img.onerror = () => reject(new Error('图片加载失败'));
    img.src = url;
  });
}

/**
 * 压缩图片
 * @param file 图片文件
 * @param maxWidth 最大宽度
 * @param quality 压缩质量 0-1
 * @returns Promise<Blob>
 */
export function compressImage(file: File, maxWidth: number = 1200, quality: number = 0.8): Promise<Blob> {
  return new Promise((resolve, reject) => {
    const img = new Image();
    const reader = new FileReader();

    reader.onload = (e) => {
      if (!e.target?.result) {
        reject(new Error('文件读取失败'));
        return;
      }

      img.src = e.target.result as string;
    };

    reader.onerror = () => reject(new Error('文件读取错误'));

    img.onload = () => {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');

      if (!ctx) {
        reject(new Error('无法获取canvas上下文'));
        return;
      }

      // 计算新尺寸
      let { width, height } = img;
      if (width > maxWidth) {
        height = (height * maxWidth) / width;
        width = maxWidth;
      }

      canvas.width = width;
      canvas.height = height;

      // 绘制并压缩
      ctx.drawImage(img, 0, 0, width, height);
      
      canvas.toBlob(
        (blob) => {
          if (blob) {
            resolve(blob);
          } else {
            reject(new Error('图片压缩失败'));
          }
        },
        'image/jpeg',
        quality
      );
    };

    img.onerror = () => reject(new Error('图片加载失败'));
    reader.readAsDataURL(file);
  });
}

/**
 * 获取图片尺寸
 * @param url 图片URL
 * @returns Promise<{width: number, height: number}>
 */
export function getImageDimensions(url: string): Promise<{ width: number; height: number }> {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => resolve({ width: img.width, height: img.height });
    img.onerror = () => reject(new Error('无法获取图片尺寸'));
    img.src = url;
  });
}

/**
 * 创建图片缩略图
 * @param url 原图URL
 * @param maxSize 最大尺寸
 * @returns Promise<string> 缩略图DataURL
 */
export async function createThumbnail(url: string, maxSize: number = 200): Promise<string> {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.crossOrigin = 'anonymous';
    
    img.onload = () => {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      
      if (!ctx) {
        reject(new Error('无法获取canvas上下文'));
        return;
      }

      // 计算缩略图尺寸
      let { width, height } = img;
      if (width > height) {
        if (width > maxSize) {
          height = (height * maxSize) / width;
          width = maxSize;
        }
      } else {
        if (height > maxSize) {
          width = (width * maxSize) / height;
          height = maxSize;
        }
      }

      canvas.width = width;
      canvas.height = height;

      ctx.drawImage(img, 0, 0, width, height);
      resolve(canvas.toDataURL('image/jpeg', 0.7));
    };
    
    img.onerror = () => reject(new Error('图片加载失败'));
    img.src = url;
  });
}
